<template>
	<view class="" >
		<uni-popup ref="popuAttrPrice" :type="'bottom'">
			<view class="popu-attr-price padding-x-30">
				<view class="iconfont icon-cha flex flex-align-items justify-content" style="background-color: #999999;color: #FFFFFF;width: 40rpx; height: 40rpx; border-radius: 100%;" @click="close"></view>
				<view class="flex flex-align-items" style="height: 260rpx;">
					<image style="height: 180rpx; width: 180rpx; border-radius: 10rpx;" :src="selectShop.defaultImage?selectShop.defaultImage:goods.spuRes.defaultImage" mode=""></image>
					<view class="padding-left-20">
						<view class="top-price main-text-color" v-if="selectShop.price">￥{{selectShop.price}}</view>
						<view class="top-price main-text-color" v-else>￥{{goods.spuRes.price}}</view>
						<view v-if="selectShop.stock">库存：{{selectShop.stock}}</view>
						<view v-else>总库存：{{goods.spuRes.stock}}</view>
						<view v-if="selectShop.skuAttrItems">
							<text class="" style="padding-right: 10rpx;" v-for="(val,key) in selectShop.skuAttrItems" :key="key">{{val}}</text>
						</view>
						<view v-else>请选择商品规格</view>
					</view>
				</view>
				<view v-for="(skuAttr,index) in dataResut.spuRes.skuAttrItems" :key="index">
					<view class="attrName">{{skuAttr.attrName}}</view>
					<view class="flex flex-align-items flex-wrap ">
						<view class=" attr-val-p" v-for="(attrVal,ind) in skuAttr.attrVal" :key="ind" @tap="skuClick(attrVal, index, ind)"
						 >
							<view class="attr-val-c" 
							:class="[attrVal.ishow ? '' : 'noactived', subIndex[index] == ind ? 'actived' : '']"
							:style="attrVal.ishow &&subIndex[index] == ind?'background-color: #FFFFFF;':''">{{attrVal.val}}</view>
						</view>
					</view>
				</view>
				<view class="flex flex-between flex-align-items">
					<view class="attrName">数量</view>
					<view class="flex flex-align-items">
						<text class="set" @tap="setNum(-1)" :style="selectNum==1||!selectShop.price?'color: #CCCCCC;':''" style="">-</text>
						<view class="Num">
							<input  type="number" v-model="selectNum" />
						</view>
						<text class="set"  @tap="setNum(1)" :style="selectShop.price&&selectShop.stock>selectNum?'':'color: #CCCCCC;'">+</text>
					</view>
				</view>
				<button class="main-bg-color submit" @tap="submit">确定</button>
			</view>
			
		</uni-popup>
	</view>
	
</template>
<script>
	import uniPopup from "../uni-popup/uni-popup.vue"
	export default {
		components:{
			uniPopup
		},
		props: {
			goods: Object
		},
		data() {
			return {
				shopItemInfo: {}, // 存放要和选中的值进行匹配的数据
				selectArr: [], // 存放被选中的值
				subIndex: [], // 是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
				selectShop: {}, // 存放最后选中的商品
				selectNum: this.minBuyNum, // 选中数量
				outFoStock: false, // 是否全部sku都缺货
				goodsInfo: {},
				minBuyNum:1,
				dataResut:this.goods//商品信息必须这么写，否则微信不兼容里面的数据变化
			}
		},
		mounted() {
			this.init()
		},
		watch:{
			selectNum(newVal,oldVal){
				
				if(this.selectShop.stock){
					 if(newVal>this.selectShop.stock){
					 	this.$nextTick(()=>{
					 		this.selectNum=this.selectShop.stock;
					 	})
					 }
					 this.$emit('selectSkuChange',this.selectShop,this.selectNum);
				}else{
					
					this.$nextTick(()=>{
						this.selectNum=1;
					})
				}
				
				
			}
		},
		methods: {
			//开启popu弹框
			open(){
				this.$refs.popuAttrPrice.open();
			},
			//关闭popu弹框
			close(){
				this.$refs.popuAttrPrice.close();
			},
			// 初始化
			init() {
				// 清空之前的数据
				this.selectArr = [];
				this.subIndex = [];
				this.selectShop = {};
				this.selectNum = 1;
				this.outFoStock = false;
				this.shopItemInfo = {};
				this.dataResut.spuRes.skuAttrItems.map(item => {
					this.selectArr.push('');
					this.subIndex.push(-1);
				});
				this.checkItem(); // 计算sku里面规格形成路径
				this.checkInpath(-1); // 传-1是为了不跳过循环
			},
			/**
			 * ------------------------------------------------------------------------------------------------------------------------------
			 * 计算sku里面规格形成路径
			 */
			checkItem() {
				let sku_list = this.dataResut.skuRes;
				// 去除库存小于等于0的商品sku
				sku_list = sku_list.filter(sku => {
					return sku.stock > 0;
				});
				//判断所有的sku库存是否都为0
				if (sku_list.length == 0) {
					this.outFoStock = true;
				}

				/**
				 * 讲解：
				 * returnVals表示初始化的值，或者上一次调用的返回值
				 * currentValue表示sku_list集合中，当前遍历的元素
				 * [[]]表示初始的returnVals是一个二维数组
				 * sku_list.reduce((returnVals,currentValue)=>{
				 *  },[[]])
				 * -------------------------------------------------------------------------------------------------------
				 * prev【表示初始值[]空数组】    [表示上一次调用返回的值return prev;]
				 * current 表示当前值
				 *    const str = 'hello'
					  const newstr = str.split('').reduce(function (prev, current) {
						 const obj = {};
						 obj[current] = current;
						 prev.push(obj)
						 return prev;
					  }, [])
					  console.log(newstr)
				   ------------------------------------------------------------------------------------------------------
				   prev 【初始值为0】     [表示上一次调用的返回值return prev+current]
				   current  表示遍历数组的当前值
				          const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
				          const sum = arr.reduce(function (prev, current) {
				            return prev+current
				          }, 0)
				          console.log(sum) //55
				 */
				let result = sku_list.reduce((returnVals1, currentValue1) => {
					/**
					 * 连接两个或更多的数组，接收可变参数，并返回一个新的数组。
					 */
					return returnVals1.concat(this.getSkuAttrItems(currentValue1).reduce((attrVals2, attrCurrentValue2) => {
						//拼接数组
						return attrVals2.concat(attrVals2.map(v => {
							//[...v, attrCurrentValue2]表示拼接数组啊，相当于v.push(attrCurrentValue2)
							//hasOwnProperty([...v, attrCurrentValue2])会自动将参数[...v, attrCurrentValue2]数组拼接成字符串
							//相当于hasOwnProperty([...v, attrCurrentValue2].join(","))
							if (!this.shopItemInfo.hasOwnProperty([...v, attrCurrentValue2])) {
								this.shopItemInfo[[...v, attrCurrentValue2]] = currentValue1;
							}
							return [...v, attrCurrentValue2]
						}))
					}, [
						[]
					]));
				}, [
					[]
				]);
				console.log(this.shopItemInfo)

			},
			/**
			 *获取每个sku中的skuAttrItems，并将skuAttrItems中的value返回一个数组
			 */
			getSkuAttrItems(sku) {
				let arr = [];
				for (let k in sku.skuAttrItems) {
					arr.push(sku.skuAttrItems[k])
				}
				//console.log(arr);["珍珠白","36G","20寸"]
				return arr;
			},
			/**
			 * ------------------------------------------------------------------------------------------------------------------------------
			 * 检查路径
			 */
			checkInpath(clickIndex) {
				let skuAttrItems = this.dataResut.spuRes.skuAttrItems
				/**
				 * 循环所有属性判断哪些属性可选,  当前选中的兄弟节点和已选中属性不需要循环
				 */
				for (let i = 0; i < skuAttrItems.length; i++) {
					if (clickIndex === i) {
						continue;
					}
					let attrVal = skuAttrItems[i].attrVal;
					for (let j = 0; j < attrVal.length; j++) {
						//
						if (this.subIndex[i] != -1 && j === this.subIndex[i]) {
							continue;
						}
						let choosed_copy = [...this.selectArr]; //获取之前被选中的值
						this.$set(choosed_copy, i, attrVal[j].val);
						let choosed_copy2 = choosed_copy.filter(item => item !== '' && typeof item !== 'undefined');
						
						if (this.shopItemInfo.hasOwnProperty(choosed_copy2)) {
							skuAttrItems[i].attrVal[j].ishow = true;
						} else {
							skuAttrItems[i].attrVal[j].ishow = false;
						}
					}
				}
				// this.$nextTick(()=>{
					
				// }）
				this.$set(this.dataResut.spuRes, "skuAttrItems", skuAttrItems)
			},
			/**
			 * -------------------------------------------------------------------------------------------
			 * sku按钮的点击事件
			 */
			skuClick(value, index1, index2) {
				// console.log(value)
				if (value.ishow) {
					if (this.selectArr[index1] != value.val) {
						this.$set(this.selectArr, index1, value.val);
						this.$set(this.subIndex, index1, index2);
					} else {
						this.$set(this.selectArr, index1, '');
						this.$set(this.subIndex, index1, -1);
					}
					this.checkInpath(index1);
					// 如果全部选完
					this.checkSelectShop();
				}
			},
			/**
			 * 检测是否已经选完sku
			 */
			checkSelectShop() {
				// 如果全部选完
				if (this.selectArr.every(item => item != '')) {
					this.selectShop = this.shopItemInfo[this.selectArr];
					this.selectNum = this.minBuyNum;
					this.$emit('selectSkuChange',this.selectShop,this.selectNum);
				} else {
					this.selectShop = {};
					this.$emit('selectSkuChange',{},0);
				}
			},
			// 提示信息
			showToast(){
				uni.showToast({
					title:"请选择规格",
					icon:"none"
				})
			},
			// 选中的数量发生变化
			setNum(Num){
				if(this.selectShop.stock){
					if(Num==-1){
						if(this.selectNum>1){
							this.selectNum+=Num;
						}
					}else{
						if( this.selectNum<this.selectShop.stock)
						this.selectNum+=Num;
					}
				}else{
					this.showToast()
				}
			},
			submit(){
				if(!this.selectShop.price){
					this.showToast()
				}else{
					this.$emit('submitBtn');
					this.close();
				}
			}
		}
	};
</script>

<style lang="less">
	.popu-attr-price {
		background-color: #ffffff;
		height: 1035rpx;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		position: relative;
		.icon-cha{
			float: right;
			margin-top: 20rpx;
		}
		.topInfo{
			margin-top: 80rpx;
			
		}
		.top-price{
			font-size: 30rpx;
			font-weight: 700;
		}
		.attrName {
			font-size: 30rpx;
			font-weight: 700;
		}

		.attr-val-p {
			width: 230rpx; //给固定的宽度,左右margin=30 则每个宽度就是 (750-60)/3=230，因为每行展示3个所以除3
			display: flex;
			align-items: center;
			justify-content: center;

			.attr-val-c {
				width: 70%;
				background-color: #F1F1F1;
				padding: 10rpx 20rpx;
				text-align: center;
				margin: 20rpx 0;
				border-radius: 50rpx;

			}
		}
		
	}

	.actived {
		border: 1px solid #fe560a;
		color: #fe560a;
	}

	.noactived {
		background-color: #e4e4e4;
		border: 1rpx solid #e4e4e4;
		color: #9e9e9e;
		text-decoration: line-through;
	}
	
	.set{
		padding:0rpx 20rpx;
		width: 50rpx;
		font-size: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.Num{
		width: 100rpx;
		height: 50rpx;
		background-color: #F1F1F1;
		input{
			font-size: 30rpx;
			display: flex;
			height: 100%;
			text-align: center;
		}
	}
	
	.submit{
		color: #FFFFFF;font-size: 30rpx;
		font-weight: 700;
		border-radius: 50rpx;
		position: absolute;
		left: 0;
		bottom: 20rpx;
		width: 90%;
		margin-left: 5%;
		
	}
</style>
